var appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

    order_id:'',
    order:{

    },
    order_total:{
      shipping:0,
      goods:0,
      total:0,
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      order_id:options.order_id
    });
    this.order_info();

  },

  order_info:function(){

    var t = this;
    var url = appInstance.globalData.api_path + '&r=checkout.order.info';
    var data = {
      order_id:this.data.order_id,
    };

    appInstance.request(url, data, "GET", res => {

      console.log( res.data );
      if( !res.data.status ){

        res.data.order.total.forEach(function( item ){

          if( item.code == 'shipping' ){
            t.data.order_total.shipping = item.value;
          }
          if( item.code == 'goods' ){
            t.data.order_total.goods = item.value;
          }
          if( item.code == 'total' ){
            t.data.order_total.total = item.value;
          }

        });
        t.setData({
          order: res.data.order,
          order_total: t.data.order_total
        });
      }

    });


  },

  gotoBuy:function( e ){

    var url = appInstance.globalData.api_path+'&r=checkout.xpay.index_xcx';

    var data = {
      order_id: e.currentTarget.dataset.order.id,
    };

    var t = this;
    appInstance.request( url, data, 'GET', res=>{

      if( res.data.nonceStr ){
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success (res) {

            t.pay_notify();
            // t.order_info();
          },
          fail (res) {

          }
        });

      }


    });

  },

  pay_notify:function( order ){

    var t = this;
    var url = appInstance.globalData.api_path+'&r=checkout.xpay.pay_notify';
    var data = {
      'order_id' : order.id
    };
    appInstance.request( url, data, 'POST', function(){

      t.order_info();
      // order.is_payed = 1;
      // t.setData({
      //   order:order
      // });

    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})